# coding=utf-8
# IP变动检测
from ip.ip import IP
from mailServer.qqMail import QQMail
import time
from logger.familyLogger import FamilyLogger


class IpCheck(object):
    logger = FamilyLogger().getLogger("ip_check")
    mailTitle = '家庭云IP变动通知'  # 邮件标题
    mailContent = '家庭云IP地址已变动\n新IP：{new_ip}\n历史IP：{old_ip}'  # 邮件内容模板
    msg_from = '995028563@qq.com'  # 发送邮箱
    pass_key = 'yjqysmefuifwbdjg'  # 发送邮箱授权码
    msg_to = '1025684257@qq.com'  # 接收邮箱
    old_ip = ''  # 上次检测IP地址
    state = 0  # 运行状态；0：未运行；1：正在运行

    def check_ip(self):
        """检测IP"""
        my_ip = IP.get_ip()
        self.logger.info("IP：" + my_ip)
        if self.old_ip != my_ip:
            mail = QQMail(self.msg_from,self.pass_key,self.msg_to)
            mail.send(self.mailTitle,self.mailContent.replace('{new_ip}',my_ip).replace('{old_ip}',self.old_ip))
            self.old_ip = my_ip
            self.logger.info("IP已更新")

    def run(self):
        """ 运行IP检测 """
        self.logger.info("启动IP检测程序.....")
        self.state = 1
        while self.state == 1:
            self.check_ip()
            time.sleep(5*60)

    def stop(self):
        """ 停止IP检测 """
        self.logger.info("停止IP检测程序.....")
        self.state = 0


IpCheck().run()
